package fu.capstone.hanoicityguide.dataaccess.commondialogue;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import fu.capstone.hanoicityguide.R;
import fu.capstone.hanoicityguide.business.model.CommonDialogue;
import fu.capstone.hanoicityguide.dataaccess.base.BaseDAOImpl;
import fu.capstone.hanoicityguide.dataaccess.base.DatabaseHelper;

public class CommonDialogueDAOImp extends BaseDAOImpl implements
		CommonDialogueDAO {

	private SQLiteDatabase database;
	private DatabaseHelper dbHelper;
	private Context ctx;

	public CommonDialogueDAOImp(Context ctx) {
		super(ctx);
		// TODO Auto-generated constructor stub
		this.ctx = ctx;
	}

	@Override
	public ArrayList<CommonDialogue> listCommonDialogue(String keyword,
			String sorter) {
		// TODO Auto-generated method stub
		Cursor cursor = null;
		ArrayList<CommonDialogue> arrResult = new ArrayList<CommonDialogue>();

		try {
			dbHelper = connectDB();
			database = dbHelper.getReadableDatabase();
			String queryCommonDialogue = "SELECT CommonDialogue.[Id], CommonDialogue.[VietnameseContent], "
					+ "CommonDialogue.[EnglishContent], CommonDialogue.[AudioPath] FROM CommonDialogue ";
			// filter by keyword
			queryCommonDialogue = queryCommonDialogue
					+ "WHERE CommonDialogue.[EnglishContent] LIKE '%" + keyword
					+ "%' ";
			queryCommonDialogue = queryCommonDialogue
					+ " OR CommonDialogue.[VietnameseContent] LIKE '%"
					+ keyword + "%' ";
			// sort
			if (sorter.equals(ctx.getResources().getStringArray(
					R.array.sorter_items)[2])) {
				queryCommonDialogue = queryCommonDialogue
						+ "ORDER BY CommonDialogue.[EnglishContent] DESC";
			} else if (sorter.equals(ctx.getResources().getStringArray(
					R.array.sorter_items)[3])) {
				queryCommonDialogue = queryCommonDialogue
						+ "ORDER BY CommonDialogue.[EnglishContent] ASC";
			}

			cursor = database.rawQuery(queryCommonDialogue, null);
			if (cursor != null) {
				if (cursor.moveToFirst()) {
					do {
						CommonDialogue cDialogue = new CommonDialogue();
						cDialogue.setId(cursor.getInt(cursor
								.getColumnIndex("Id")));
						cDialogue.setVietnameseContent(cursor.getString(cursor
								.getColumnIndex("VietnameseContent")));
						cDialogue.setEnglishContent(cursor.getString(cursor
								.getColumnIndex("EnglishContent")));
						cDialogue.setAudioPath(cursor.getString(cursor
								.getColumnIndex("AudioPath")));
						arrResult.add(cDialogue);
					} while (cursor.moveToNext());
				}
			}
		} catch (Exception e) {
			Log.v("Can't query DB", e.toString());
		} finally {
			closeDB(database, dbHelper);
		}
		return arrResult;

	}

}
